package com.wlj.rbac;


import com.google.common.collect.Lists;
import com.wlj.dto.UserMenuDTO;
import com.wlj.dto.UserResourcesDTO;
import com.wlj.pojo.TbMenu;
import com.wlj.pojo.TbResource;
import com.wlj.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Component("rbacService")
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Autowired
    private UserService userService;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission=false;
        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            ArrayList<? extends GrantedAuthority> authorities = Lists.newArrayList(userDetails.getAuthorities());
            List<String> collect = authorities.stream().map(e -> e.getAuthority()).collect(Collectors.toList());
            Set<String> urls = new HashSet<>(collect);
            //共有权限
            urls.add("GET_/");
            urls.add("GET_/index.html");
            urls.add("GET_/home.html");
            for (String url : urls) {
                String[] url2 = url.split("_");
                if(antPathMatcher.match(url2[1],request.getRequestURI())&&url2[0].equalsIgnoreCase(request.getMethod())){
                    hasPermission=true;
                    break;
                }
            }

        }
        return hasPermission;
    }
}
